import 'dart:convert';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_validate.dart';
import 'package:get/get.dart';
import '../../../../lib_basemodel/chat_room/kh_chat_room_seat_model.dart';
import '../../../../lib_baseview/provider.dart';
import '../../../../lib_baseview/widget/dialogs.dart';
import '../../../../lib_im/index.dart';
import '../../../../lib_network/http_api.dart';
import '../../../../lib_network/http_helper.dart';
import '../../../../lib_runtime/logger.dart';
import 'package:crypto/crypto.dart';
import 'package:encrypt/encrypt.dart' as encrypt; // 使用别名导入

class GiftPageModel extends JRChangeNotifier {
  // GiftScene scene = GiftScene.private_chat;

  final giftNumbers = [1, 7, 17, 77, 777];

  /// 选中的礼物数量
  int giftCount = 1;
  void setGiftCount(int count) {
    if (count == giftCount) return;
    giftCount = count;
    notifyListeners();
  }

  /// 当前选中的礼物
  ImGitfModel? curSelectGiftModel;

  bool _isLoading = true;
  bool get isLoading => _isLoading;

  List<KHChatRoomSeatModel?> userList = [];
  List<KHChatRoomSeatModel?> selectedUserList = [];

  List<ImGitfWrapperModel> tabList = [];
  int totalCoin = 0;

  /// 是否赠送所有在麦位上的人
  bool _isGiveAll = false;
  bool get isGiveAll => _isGiveAll;
  set isGiveAll(bool value) {
    _isGiveAll = value;
    notifyListeners();
  }

  // ItemInfo? get currGift => _currentGroupInfo?.currGift;
  int? currentGiftID; //当前赠送的心愿礼物ID
  List<String> giftNumberList = [];
  int selectedGiftNum = 0;
  String? roomNo; //房间ID
  // Channel? channel;
  int coin = 0;
  //当前选中tab
  ImGitfWrapperModel? _currentGroupInfo;

  // bool get showUserList =>
  //     giftUserList.isNotEmpty && scene == GiftScene.chatroom;

  int get currentTabIndex => _currentGroupInfo == null
      ? 0
      : max(tabList.indexOf(_currentGroupInfo!), 0);

  ValueChanged<int>? tabValueChange;
  var isSelectingGiftNum = false;
  // bool get fromRoom => scene == GiftScene.chatroom;
  Color get bgColor => const Color(0xFF241235);
  Color get textColor => Colors.white;
  // bool get needShowCpUser =>
  //     fromRoom &&
  //     RootProxyModel.instance?.channelExt.value?.cpInfo.stage ==
  //         CPStage.introduce;
  // CpRoomOtherHeartResp? otherHeartResp;
  // bool get showCpUser => needShowCpUser && (otherHeartResp?.heartList.isNotEmpty == true);

  ValueChanged<List<ImGitfWrapperModel>>? onLoadTabCompleted;

  // bool get cpRoom => false;

  ///是否有权利赠送
  // bool get hasRightSend {
  //   if ((currGift?.knightLevel ?? 0) > 0) {
  //     return UserManager.instance.currentUser!.knightLevel >=
  //         currGift!.knightLevel;
  //   }
  //   return true;
  // }

// currentTabIndex
  // late TabController giftTabController;
  List<ImGitfModel> gifts = [];

  /// 有多少个分类
  List<ImGitfWrapperModel> wrappers = [];

  final balance = ValueNotifier<int?>(null);

  GiftPageModel() {
    getGiftData();
    _getBalance();
  }

  /// 获取当前余额
  void _getBalance() async {
    final value = await ImAPI.getBalance();
    balance.value = value;
    notifyListeners();
  }

  set currentGroupInfo(ImGitfWrapperModel? currentGroupInfo) {
    _currentGroupInfo = currentGroupInfo;
    notifyListeners();
  }

  List<ImGitfModel> getGifts(ImGitfWrapperModel wrapper) {
    final ids = wrapper.giftVos.map((e) => e.id).toList();
    final matchedGifts = gifts.where((gift) => ids.contains(gift.id)).toList();
    return matchedGifts;
  }

  void initSelectedUserList() {
    // if (scene == GiftScene.private_chat) {
    //   selectedUserList = giftUserList.toList();
    // } else {
    //   // if (giftUserList.length == 1) {
    //   selectedUserList = giftUserList.toList();
    //   // }
    // }
    // log("initSelectedUserList scene: $scene, selectedUserList: $selectedUserList"
    //     ", giftUserList: $giftUserList");
  }

  void getCoin() async {
    // var result = await CashApi.instance.getCurrUserCash();
    // if (!result.isSuccess) {
    //   showToast(T.current.get_data_fail);
    //   return;
    // }
    // coin = (result.data!.coin).toInt();
    // notifyListeners();
  }

  getGiftData() async {
    try {
      _isLoading = true;
      notifyListeners();

      final results = ImAPI.giftLocalList();
      gifts = results.$1;
      wrappers.assignAll(results.$2);

      initData(gifts, wrappers);
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  initData(
      List<ImGitfModel> giftList, List<ImGitfWrapperModel> wrappers) async {
    // var wrappers = <ImGitfWrapperModel>[].obs;

    if (tabList.isEmpty) {
      //第一次
      tabList = wrappers;
      onLoadTabCompleted?.call(tabList);
      _currentGroupInfo ??= tabList[0];
      for (var tab in tabList) {
        // tab.currGift = tab.giftList.firstOrNull;
      }
      if (currentGiftID != null) {
        setDefaultWishGiftsSelect(currentGiftID);
      }
      //设置逗币数量
      getCoin();
      giftNumberList = ["1", "3", "10", "40", "100", "999"];
      selectedGiftNum = int.parse(giftNumberList.firstOrNull ?? "0");
    } else {
      //更新
      List<ImGitfWrapperModel> tempGift = tabList;
      tabList = wrappers;
      onLoadTabCompleted?.call(tabList);
      // for (var tab in tabList) {
      //   tab.currGift = tab.giftList.firstOrNull;
      //   //数据更新是 保留之前选中的item
      //   for (var oldTab in tempGift) {
      //     if (oldTab.id == tab.id) {
      //       tab.currGift = oldTab.currGift;
      //     }
      //   }
      // }
    }

    notifyListeners();
  }

  _getOtherHeart() async {
    // var result = await CashApi.instance.otherHeart(channelId?.toInt() ?? 0);
    // if (result.isSuccess) {
    //   otherHeartResp = result.data;
    // }
    notifyListeners();
  }

  int getOtherHeartWithUid(int uid) {
    // if (needShowCpUser) {
    //   OtherHeartItem? item = otherHeartResp?.heartList
    //       .firstWhereOrNull((element) => element.uid.toInt() == uid);
    //   if (item != null) {
    //     return item.heart.toInt();
    //   }
    // }
    return -1;
  }

  bool isFirstHeartUid(int uid) {
    // if (needShowCpUser) {
    //   var maxHeart = 0;
    //   var maxUid = 0;
    //   otherHeartResp?.heartList.forEach((_) {
    //     if (_.heart.toInt() > maxHeart) {
    //       maxHeart = _.heart.toInt();
    //       maxUid = _.uid.toInt();
    //     }
    //   });
    //   return uid == maxUid;
    // }
    return false;
  }

  //心愿礼物赠送,默认选中赠送的礼物
  setDefaultWishGiftsSelect(int? giftsId) {
    // for (var currTab in tabList) {
    //   ItemInfo? selectItem = currTab.giftList
    //       .firstWhereOrNull((element) => element.id.toInt() == giftsId);
    //   if (selectItem != null) {
    //     currTab.currGift = selectItem;
    //     _currentGroupInfo = currTab;
    //     tabValueChange?.call(currentTabIndex);

    //     notifyListeners();
    //     break;
    //   }
    // }
  }

  void selectAllGiftUser() {
    if (selectedUserList.length == userList.length &&
        selectedUserList.isNotEmpty) {
      log("selectAllGiftUser unselect all");
      selectedUserList.clear();
    } else {
      log("selectAllGiftUser select all");
      selectedUserList.clear();
      selectedUserList.addAll(userList);
    }
    notifyListeners();
  }

  //是否已经全选
  bool isSelectAll() {
    print('selectedUserList${selectedUserList.length} ${userList.length}');
    return selectedUserList.length == userList.length;
    // return false;
  }

  void log(String? msg) {
    RLog.i("$runtimeType $msg");
  }

  void selectGiftUser(KHChatRoomSeatModel user) {
    if (!selectedUserList.contains(user)) {
      selectedUserList.add(user);
    } else {
      selectedUserList.remove(user);
    }
    notifyListeners();
  }

  int giftCost() {
    // if (currGift == null) return 0;
    // return (currGift!.price).toInt() * selectedGiftNum;
    return 1;
  }

  // void updateCurrGift(ItemInfo itemInfo, GiftGroupInfo groupInfo) {
  //   if (itemInfo == currGift) {
  //     return;
  //   }
  //   _currentGroupInfo = groupInfo;
  //   _currentGroupInfo?.currGift = itemInfo;
  //   notifyListeners();
  // }

  void updateGiftNum(int giftNum) {
    if (selectedGiftNum == giftNum) {
      return;
    }
    selectedGiftNum = giftNum;
    notifyListeners();
  }

  void buyGifts(BuildContext context) async {
    // if (UserManager.instance.isSuperAdmin) {
    //   showToast(T.current.cant_package_gift);
    //   return;
    // }
    // if (selectedGiftNum <= 0 && currGift == null) {
    //   showToast(T.current.select_gift_first);
    //   return;
    // }
    // if (selectedUserList.isEmpty) {
    //   showToast(T.current.select_gift_receiver);
    //   return;
    // }

    // var totalPrice =
    //     selectedUserList.length * selectedGiftNum * currGift!.price.toInt();
    // if (coin < totalPrice) {
    //   RechargeDialog.showWithBottomSheet(context,
    //       source: ChargeSource.SEND_GIFT,
    //       price: totalPrice, onRechargeSuccess: () {
    //     //充值成功，刷新数据
    //     getCoin();
    //   });
    //   return;
    // }

    // ItemInfo gift = currGift!;
    // List<$fixnum.Int64> receiveIdList = selectedUserList
    //     .map((e) => $fixnum.Int64.parseInt(e.userId ?? "0"))
    //     .toList();
    // var tempChannelId = scene == GiftScene.chatroom ? channelId : null;
    // var result = await CashApi.instance
    //     .giveGift(receiveIdList, gift.id, selectedGiftNum, tempChannelId);
    // if (!result.isSuccess) {
    //   showToast(result.errorMsg ?? T.current.gift_gift_faile);
    //   // dismissLoadingDialog();
    //   return;
    // }
    // if (!mounted) {
    //   return;
    // }
    // eventCenter.emit(Event(EventConstant.sendGiftSuccess,
    //     data: {'url': gift.dynamicResource, 'scene': scene}));
    // showToast(T.current.gift_gift_suc);
    // if (needShowCpUser) {
    //   _getOtherHeart();
    // }
    // if (receiveIdList.isNotEmpty) {
    //   for (var element in selectedUserList) {
    //     Map<String, dynamic> map = {};
    //     map["to_uid"] = element.userId.toString();
    //     map["gift_id"] = currGift!.id.toString();
    //     map["gift_name"] = currGift!.name;
    //     map["price"] = currGift!.price.toInt();
    //     map["num"] = selectedGiftNum;
    //     map["money"] = selectedGiftNum * currGift!.price.toInt();
    //     map["scene"] = scene.name;

    //     if (scene == GiftScene.chatroom) {
    //       map["rid"] = channel!.channelId.toInt();
    //       map["room_type"] = channel!.roomTypeObj.name;
    //       map["channel_type"] = "${channel!.roomLabel}";
    //       map["use_type"] = "${channel!.usage}";
    //       map["is_work"] = channel!.inProcessOfSchedule;
    //       map["owner_uid"] = channel!.owner.id.toString();
    //     }

    //     // Reporter.track(TrackEvent.sendGift, map);
    //   }
    // }

    // getCoin();
    // // dismissLoadingDialog();
    // if (!mounted) {
    //   return;
    // }
    // Navigator.of(context).pop();
  }

  bool get showBottomBar {
    // String? type = _currentGroupInfo?.tabType;
    // return type == GiftGroupInfo.typeHot ||
    //     type == GiftGroupInfo.typeHorizontal ||
    //     type == GiftGroupInfo.typePrivilege;

    return true;
  }

  /// 选中的礼物
  int? _selectedGiftId; // 当前选中礼物ID
  void selectGift(int giftId) {
    if (_selectedGiftId == giftId) {
      _selectedGiftId = null;
    } else {
      _selectedGiftId = giftId;
    }
    notifyListeners();
  }

  // 判断是否选中
  bool isGiftSelected(ImGitfModel gift) {
    if (_selectedGiftId == gift.id) {
      curSelectGiftModel = gift;
      return true;
    } else {
      return false;
    }
  }

// model.selectedUserList
  /// 调用赠送礼物接口
  void sendRoomGift(
    List<KHChatRoomSeatModel?> userList,
    String? roomNo,
    ImGitfModel? giftModel,
    int giftCount, {
    void Function(bool success)? callback,
  }) async {
    List<int> useridList = userList
        .where((user) => user?.micUser?.userId != null)
        .map((user) => user!.micUser!.userId!)
        .toList();

    if (userList.isEmpty) {
      return;
    }
    // 将 useridList 转换为以逗号分隔的字符串
    String useridString = useridList.map((id) => id.toString()).join(',');

    String timeStr = DateTime.now().millisecondsSinceEpoch.toString();

    var res = await HttpHelper.instance().post(
      HttpApi.discoverSendGift,
      body: {
        'roomNo': roomNo,
        "userIds": useridString,
        "productId": giftModel!.id,
        "amount": giftCount,
        "timestamp": timeStr,
        "actionType": 1,
        "price": giftModel.price,
      },
      showLoading: false,
      showToast: true,
    );

    if (res.isSuccess) {
      String keyStr = "";
      if (timeStr.length >= 8) {
        keyStr += timeStr[1];
        keyStr += timeStr[3];
        keyStr += timeStr[5];
        keyStr += timeStr[7];
      }

      // 计算 MD5 哈希值
      var bytes = utf8.encode(keyStr);
      var digest = md5.convert(bytes);
      String md5Str = digest.toString();
      String aesKeyStr = md5Str.substring(0, 16);

      // 创建 AES 解密器
      final key = encrypt.Key.fromUtf8(aesKeyStr); // 使用别名调用 Key
      final iv = encrypt.IV.fromLength(16); // 使用别名调用 IV
      final encrypter = encrypt.Encrypter(
          encrypt.AES(key, mode: encrypt.AESMode.ecb)); // 使用别名调用相关类

      // 解密数据
      try {
        final encrypted =
            encrypt.Encrypted.fromBase64(res.result); // 使用别名调用 Encrypted
        String jsonStr = encrypter.decrypt(encrypted, iv: iv);

        // 解析 JSON 字符串
        Map<String, dynamic>? map = json.decode(jsonStr);
        if (map == null) {
          callback?.call(false);
          return;
        }
        String? signature = map!['signature'];
        if (signature == null) {
          /// 赠送礼物失败
          showToast('赠送礼物失败');
          callback?.call(false);
          return;
        }

        String endStr = '$timeStr${map['echostr']}'.toMd5();
        if (endStr.toLowerCase() == signature.toLowerCase()) {
          _getBalance();
          callback?.call(true);
        } else {
          callback?.call(false);
        }
      } catch (e) {
        throw Exception(e);
      }
    } else {
      showToast('赠送礼物失败');
      callback?.call(false);
    }
  }

  @override
  void dispose() {
    dismissLoadingDialog();
    super.dispose();
  }
}
